package com.epfuse.cloud.common.redis.serializer.impl;


import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.epfuse.cloud.common.redis.serializer.AbstractRedisSerializer;
import com.epfuse.cloud.common.redis.serializer.annotation.EpfuseRedisSerializer;

import com.epfuse.cloud.common.redis.serializer.enums.SerializerType;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


/**
 * @Author 孙峰
 */
@EpfuseRedisSerializer(serializer = SerializerType.HESSIAN)
public class HessianSerializer extends AbstractRedisSerializer {
    @Override
    public byte[] serialize(Object obj) throws SerializationException {
        if (isEmpty(obj)) {
            return EMPTY_ARRAY;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Hessian2Output ho = new Hessian2Output(os);
        try {
            ho.writeObject(obj);
            ho.flush();
            byte[] result = os.toByteArray();
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                ho.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (isEmpty(bytes)) {
            return null;
        }
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        Hessian2Input hi = new Hessian2Input(is);
        Object t = null;
        try {
            t = (Object) hi.readObject();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return t;
    }

}